<template>
  <div class="leave-list-page">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">请假记录</h1>
      </div>
    </div>

    <el-skeleton v-if="loading" rows="4" animated style="margin: 24px 0" />
    <div v-else>
      <div v-if="leaves.length === 0" class="empty">
        <el-icon><Document /></el-icon>
        <div class="text">暂无请假记录</div>
      </div>
      <div v-else class="list">
        <div class="leave-card" v-for="item in leaves" :key="item.id" @click="openDetail(item)">
          <div class="card-header">
            <div class="status-badge" :class="'status-' + (item.status ?? 2)">
              {{ statusMap[item.status]?.text || '待审批' }}
            </div>
          </div>
          
          <div class="card-content">
            <div class="info-row">
              <span class="label">姓名</span>
              <span class="value">{{ currentUserName }}</span>
            </div>
            
            <div class="info-row">
              <span class="label">请假时间</span>
              <span class="value">{{ formatDateRange(item.startTime || item.leaveTime, item.endTime || item.backTime) }}</span>
            </div>
            
            <div class="info-row">
              <span class="label">请假时长</span>
              <span class="value">{{ calcDays(item.startTime || item.leaveTime, item.endTime || item.backTime) }}天{{ calcHours(item.startTime || item.leaveTime, item.endTime || item.backTime) }}小时</span>
            </div>
            
            <div class="info-row">
              <span class="label">请假原因</span>
              <span class="value">{{ getLeaveTypeText(item.type || item.leaveType) }}</span>
            </div>
          </div>
        </div>
      </div>
      <el-pagination
        v-if="total > pageSize"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="onPageChange"
        class="pagination"
      />
    </div>
    
    <!-- 底部提交请假按钮 -->
    <div class="bottom-submit">
      <button class="submit-btn" @click="router.push('/leave')">
        提交请假
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Document } from '@element-plus/icons-vue'
import { listLeave, getLeave } from '@/api/leave/leave'
import { getUserInfo, getUserDetailInfo } from '@/utils/auth'

const router = useRouter()

const loading = ref(true)
const leaves = ref([]) // 当前页显示的数据
const allLeaves = ref([]) // 所有用户的请假数据
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(8)
const currentUserName = ref('未知用户') // 当前用户姓名

const statusMap = {
  0: { text: '通过', color: '#52c41a', bg: 'rgba(82,196,26,0.10)' },
  1: { text: '拒绝', color: '#ff4d4f', bg: 'rgba(255,77,79,0.10)' },
  2: { text: '待审批', color: '#faad14', bg: 'rgba(250,173,20,0.10)' },
  3: { text: '已销假', color: '#1890ff', bg: 'rgba(24,144,255,0.10)' }
}

// 请假类型映射
const leaveTypeMap = {
  0: '事假',
  1: '病假',
  2: '年假',
  3: '调休',
  4: '其他'
}

// 获取请假类型文本
const getLeaveTypeText = (type) => {
  return leaveTypeMap[type] || '事假'
}

const format = (s) => {
  if (!s) return ''
  const d = new Date(String(s).replace('T', ' ').split('+')[0].split('.')[0])
  if (isNaN(d.getTime())) return s
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

const calcDays = (s, e) => {
  if (!s || !e) return 0
  const start = new Date(String(s).replace('T', ' ').split('+')[0].split('.')[0])
  const end = new Date(String(e).replace('T', ' ').split('+')[0].split('.')[0])
  if (isNaN(start.getTime()) || isNaN(end.getTime())) return 0
  const diff = (end - start) / (1000 * 60 * 60 * 24)
  return diff > 0 ? Math.floor(diff) : 0
}

const calcHours = (s, e) => {
  if (!s || !e) return 0
  const start = new Date(String(s).replace('T', ' ').split('+')[0].split('.')[0])
  const end = new Date(String(e).replace('T', ' ').split('+')[0].split('.')[0])
  if (isNaN(start.getTime()) || isNaN(end.getTime())) return 0
  const diff = (end - start) / (1000 * 60 * 60)
  const days = Math.floor(diff / 24)
  const hours = Math.floor(diff % 24)
  return hours
}

const formatDateRange = (start, end) => {
  if (!start || !end) return ''
  const s = format(start)
  const e = format(end)
  // 提取日期和时间部分
  const startDate = s.split(' ')[0]
  const startTime = s.split(' ')[1]
  const endDate = e.split(' ')[0]
  const endTime = e.split(' ')[1]
  
  if (startDate === endDate) {
    return `${startDate} ${startTime}至${endTime}`
  } else {
    return `${startDate} ${startTime}至${endDate} ${endTime}`
  }
}

const fetchLeaves = async () => {
  loading.value = true
  try {
    // 获取当前用户信息
    let currentUser = getUserInfo()
    let currentUserId = null
    
    // 如果从userInfo获取不到，尝试从userDetailInfo获取
    if (!currentUser || !currentUser.userId) {
      const userDetailInfo = getUserDetailInfo()
      if (userDetailInfo) {
        if (userDetailInfo.user && userDetailInfo.user.userId) {
          currentUserId = userDetailInfo.user.userId
          // 获取用户姓名
          currentUserName.value = userDetailInfo.user.nickName || 
                                 userDetailInfo.user.realName || 
                                 userDetailInfo.user.userName || 
                                 '未知用户'
        } else if (userDetailInfo.userId) {
          currentUserId = userDetailInfo.userId
          // 获取用户姓名
          currentUserName.value = userDetailInfo.nickName || 
                                 userDetailInfo.realName || 
                                 userDetailInfo.userName || 
                                 '未知用户'
        }
      }
    } else {
      currentUserId = currentUser.userId
      // 获取用户姓名
      currentUserName.value = currentUser.nickName || 
                             currentUser.realName || 
                             currentUser.userName || 
                             '未知用户'
    }
    
    // 如果无法获取用户ID，说明用户未正确登录，显示空列表
    if (!currentUserId) {
      console.warn('无法获取当前用户ID，请重新登录')
      leaves.value = []
      allLeaves.value = []
      total.value = 0
      loading.value = false
      return
    }
    
    // 构建查询参数，获取大量数据（不分页或设置大的pageSize）
    const query = { 
      pageNum: 1, 
      pageSize: 1000 // 设置一个较大的值来获取所有数据
    }
    
    const res = await listLeave(query)
    
    if (res.code === 200) {
      let allData = res.rows || []
      
      // 前端过滤，只保留当前用户的请假记录
      const filteredLeaves = allData.filter(leave => {
        // 检查多种可能的用户ID字段
        const leaveUserId = leave.userId || 
                           leave.cLeaveUser?.userId || 
                           leave.user?.userId ||
                           leave.user?.id
        
        return leaveUserId == currentUserId
      })
      
      // 排序逻辑：主要按状态排序（待审核2 > 已销假3 > 通过0 > 拒绝1），次要按ID倒序
      const sortedLeaves = filteredLeaves.sort((a, b) => {
        // 主要排序：按状态优先级排序
        if (a.status !== b.status) {
          // 定义状态优先级：待审核 > 已销假 > 通过 > 拒绝
          const statusPriority = { 2: 0, 3: 1, 0: 2, 1: 3 }
          const priorityA = statusPriority[a.status] !== undefined ? statusPriority[a.status] : 999
          const priorityB = statusPriority[b.status] !== undefined ? statusPriority[b.status] : 999
          return priorityA - priorityB
        }
        // 次要排序：ID倒序（新的在前）
        return b.id - a.id
      })
      
      // 存储所有过滤和排序后的数据
      allLeaves.value = sortedLeaves
      total.value = sortedLeaves.length
      
      // 计算当前页的数据
      updateCurrentPageData()
    } else {
      leaves.value = []
      allLeaves.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取请假记录时出错:', error)
    leaves.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 更新当前页显示的数据
const updateCurrentPageData = () => {
  const start = (pageNum.value - 1) * pageSize.value
  const end = start + pageSize.value
  leaves.value = allLeaves.value.slice(start, end)
}

const onPageChange = (p) => { 
  pageNum.value = p
  updateCurrentPageData()
}

const openDetail = (item) => {
  // 跳转到编辑页面，传递请假ID和状态
  router.push({
    path: '/leave',
    query: {
      id: item.id,
      status: item.status,
      mode: 'edit'
    }
  })
}

onMounted(() => {
  fetchLeaves()
})
</script>

<style lang="scss" scoped>
.leave-list-page {
  min-height: 100vh;
  padding-top: 60px;
  padding-bottom: 90px;
  background: #ffffff;
  margin: -20px;
  padding-left: 0;
  padding-right: 0;
}

.page-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  z-index: 1000;
  
  .header-content {
    text-align: center;
    
    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
      line-height: 1.4;
    }
  }
}
.empty {
  text-align: center; color: #bbb; padding: 60px 0;
  .el-icon { font-size: 40px; margin-bottom: 12px; }
  .text { font-size: 16px; }
}
.list {
  display: flex; 
  flex-direction: column; 
  gap: 12px;
  padding: 12px;
}

.leave-card {
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transform: translateY(-1px);
  }
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 12px 20px 8px;
  
  .status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
    
    &.status-0 { 
      background: rgba(82,196,26,0.1); 
      color: #52c41a; 
    }
    &.status-1 { 
      background: rgba(255,77,79,0.1); 
      color: #ff4d4f; 
    }
    &.status-2 { 
      background: rgba(250,173,20,0.1); 
      color: #faad14; 
    }
    &.status-3 { 
      background: rgba(24,144,255,0.1); 
      color: #1890ff; 
    }
  }
}

.card-content {
  padding: 12px 20px 16px;
  
  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f8f8f8;
    
    &:last-child {
      border-bottom: none;
      padding-bottom: 4px;
    }
    
    .label {
      font-size: 14px;
      color: #666;
      font-weight: 500;
      min-width: 80px;
    }
    
    .value {
      font-size: 14px;
      color: #333;
      text-align: right;
      flex: 1;
      word-break: break-all;
    }
  }
}
.pagination {
  margin: 12px 0 4px 0; 
  display: flex; 
  justify-content: center;
}

.bottom-submit {
  position: fixed;
  bottom: 64px;
  left: 0;
  right: 0;
  background: transparent;
  padding: 0;
  z-index: 100;
  
  .submit-btn {
    width: 100%;
    height: 48px;
    background: linear-gradient(135deg, #00d4aa 0%, #00b8d4 100%);
    color: white;
    border: none;
    border-radius: 0;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      background: linear-gradient(135deg, #00c19a 0%, #00a5c4 100%);
    }
    
    &:active {
      background: linear-gradient(135deg, #00b8a0 0%, #0095b4 100%);
    }
  }
}

@media (max-width: 768px) {
  .leave-list-page { 
    padding-top: 56px;
    padding-bottom: 90px;
    margin: -15px;
    padding-left: 0;
    padding-right: 0;
  }
  
  .page-header {
    padding: 12px 16px;
    
    .page-title {
      font-size: 16px;
    }
  }
  
  .list {
    padding: 8px;
    gap: 8px;
  }
  
  .leave-card {
    border-radius: 8px;
  }
  
  .pagination {
    margin: 12px 0 4px 0;
  }
  
  .bottom-submit {
    bottom: 64px;
    
    .submit-btn {
      height: 44px;
      font-size: 15px;
    }
  }
}
</style>


